package com.csun.cmny.provider.device.patrol;

import com.csun.cmny.provider.device.patrol.entity.PatrolCmdEntity;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2021/7/22 13:34
 * @Description: 巡更棒消息解码器
 */
@Slf4j
public class PatrolMessageDecoder {

    /**
     * 解析巡更棒数据
     *
     * @param data  接收到的数据
     *
     * @return  the patrol cmd entity
     *
     * 巡检器向服务器发送 数据格式都是由 数据头+命令字节+长度+数据内容+校验＋结尾
     * ----------------------------------------------------------------------
     *  0xbb 0xbb |   command |	长度  |	数据内容 |  校验 |	0x0d 0x0a |
     * ----------------------------------------------------------------------
     *  数据头字节 |	 命令字节  | 	 |			|      |    结尾      |
     * ----------------------------------------------------------------------
     */
    public static PatrolCmdEntity parse(byte[] data) {

        PatrolCmdEntity patrolCmdEntity = new PatrolCmdEntity();

        // 校验头
        int length = data.length;
        if (length < 7) {
            log.warn("=====> patrol parse error: length = {}", length);
            return null;
        }

        if (0xbb != (data[0] & 0xff) || 0xbb != (data[1] & 0xff)) {
            log.warn("=====> patrol parse error: head = {}, {}", data[0], data[1]);
            return null;
        }

        if (0x0d != data[length -2] || 0x0a != data[length - 1]) {
            log.warn("=====> patrol parse error: tail = {}, {}", data[length -2], data[length - 1]);
            return null;
        }

        // 计算校验和
        // 从数据头字节开始到校验前一个字节的异或值 再加 1
        int xor = 0x00;
        for (int i = 2; i < length - 3; i++) {
            xor = xor ^ data[i];
        }
        xor = xor + 1;

        // 消息头
        System.arraycopy(data, 0, patrolCmdEntity.head, 0, 2);

        // 命令
        patrolCmdEntity.cmd = data[2] & 0xff;

        // 长度
        patrolCmdEntity.length = data[3];

        // 校验和
        patrolCmdEntity.xor = data[length -3];

        if (patrolCmdEntity.xor != xor) {
            log.warn("=====> patrol parse error: xor = {}", xor);
        }

        // 数据内容
        int date_length = data[3]; // 长度
        if (date_length > 0) {
            patrolCmdEntity.data = new byte[date_length];   // 初始化
            System.arraycopy(data, 4, patrolCmdEntity.data, 0, date_length);
        }

        return patrolCmdEntity;
    }

    /**
     * get patrol message type
     *
     * @param msg   the patrol message
     *
     * @return  the message type
     */
    public static String getMessageType(String msg) {



        return null;
    }

    public static String format(String str) {

        String regex = "(.{2})";
        str = str.replaceAll(regex, "$1 ");
        return str;
    }
}
